package cn.edu.zafu.bigdata.yeshuchang;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;

public class TextFileOperations {

    // 写入文件的方法
    public static void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(fileName)))) {
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取文件的方法
    public static void readFromFile(String fileName) {
        try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 主方法，用于测试写入和读取文件
    public static void main(String[] args) {
        System.out.println("请输入文本，将其保存到文件中：");

        // 假设学号是2022010101，这里直接赋值，实际应用中应该让用户输入
        String studentId = "202211080107";
        String fileName = "files/" + studentId + ".txt";

        // 读取用户输入的文本
        java.util.Scanner scanner = new java.util.Scanner(System.in);
        String inputText = scanner.nextLine();

        // 将用户输入的文本写入文件
        writeToFile(fileName, inputText);

        // 读取并显示文件内容
        readFromFile(fileName);

        scanner.close();
    }
}